/* Copyright 2012 Sebastiaan Schalbroeck - schalbroeck@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nl.shinigami.afvalbak;

import java.net.URL;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MainActivity extends MapActivity implements LocationListener {
	private MapView mapView;
	private List<Overlay> mapOverlays;
	private PlacemarkOverlay itemizedoverlay;
	private LocationManager lm;
	private MapController mc;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Start location listener!
		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100,
				this);
				
		//Initialise map
		mapView = (MapView) findViewById(R.id.mapview);
		mapOverlays = mapView.getOverlays();
		mc = mapView.getController();
		mapView.setBuiltInZoomControls(true);

		Drawable drawable = this.getResources().getDrawable(R.drawable.thumb);
		itemizedoverlay = new PlacemarkOverlay(drawable, this);
		

 		// Get the last current location using the passive provider (does not need fix first)
 		Location lastloc = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
 		onLocationChanged(lastloc); //update location :D
 	
		//add our a current location blip to the map, it updates itself! ^_^
	    MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
	    myLocationOverlay.enableMyLocation();	    
	    mapOverlays.add(myLocationOverlay); 	
	    
		// Start datathread to retrieve KML data asynchronously and add data to the map
		DataThread datathread = new DataThread(this);
		datathread.execute(this.getString(R.string.dataurl));

	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private class DataThread extends AsyncTask<String, Void, List<Placemark>> {

		private Context ctx;

		public DataThread(Context ctx) {
			this.ctx = ctx;
		}

		@Override
		protected List<Placemark> doInBackground(String... params) {
			try {
				// Get URL of KML to parse
				URL sourceUrl = new URL(params[0]);

				// Prepare SAXParser
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();

				// Create handler to handle KML Tags ( extends DefaultHandler ) 
				KMLHandler kmlHandler = new KMLHandler();
				xr.setContentHandler(kmlHandler);
				
				//Parse data and get results from KMLhandler
				xr.parse(new InputSource(sourceUrl.openStream()));		
				return kmlHandler.getPlaceMarks();
				
			} catch (Exception e) {

				//Show error popup if something bad happened
				e.printStackTrace();
				Looper.prepare();
				Popup.kmlAlert((Activity) ctx);
				return null;
			}

		}

		@Override
		protected void onPostExecute(List<Placemark> results) {

			if (results != null) {
			
				//Add all placemarks to the map
				for (Placemark result : results) {
					GeoPoint point = new GeoPoint(result.getLatitude(),
							result.getLongitude());
					OverlayItem overlayitem = new OverlayItem(point,
							result.getName(), result.getDescription());
					itemizedoverlay.addOverlay(overlayitem);
				}

				mapOverlays.add(itemizedoverlay);

			}
			super.onPostExecute(results);
		}

	}

	@Override
	public void onLocationChanged(Location location) {
		
		int lat = (int) (location.getLatitude() * 1E6);
		int lng = (int) (location.getLongitude() * 1E6);
		GeoPoint point = new GeoPoint(lat, lng);
		centerLocation(point);

	}

	private void centerLocation(GeoPoint centerGeoPoint) {
	
		//Move to center and zoom if we get a new location update
		mc.animateTo(centerGeoPoint);
		mc.setZoom(14);
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
}